import { useRef, useState } from 'react'
import { useRequest, useUpdateEffect } from 'ahooks'
import dayjs from 'dayjs'
import { Button, Card, Col, DatePicker, Input, InputRef, Popconfirm, Row, theme } from 'antd'
import { EditOutlined, StopOutlined } from '@ant-design/icons'

import { Texty } from '@/components/Texty'
import { VCenterEmpty } from '@/components/VCenterEmpty'
import { useBaseInfoBoundStore } from '../BaseInfo'
import { useUrlParams } from '../utils'
import { apiGetWaybillDynamicfields, apiSaveWaybillDynamicfield } from './apis'
import { IFiled } from './interface'
import styles from './styles.module.less'

const isNotEditable = (attrKey: string) => {
  return ['运单ID', 'FBA ID', '客户', '转单号', '目的地', '预计签收日期', '状态预计完成时间', '预计DW'].includes(
    attrKey,
  )
}

export const Dynamicfields = () => {
  const { waybillNo } = useUrlParams()
  const archiveFlag = useBaseInfoBoundStore(v => v.waybillInfo?.archiveFlag)
  const { loading, data, mutate } = useRequest(() => apiGetWaybillDynamicfields(waybillNo))
  const showList = data?.filter(d => !isNotEditable(d.attrKey)) || []
  return (
    <Card className={styles.card} title="占位符" loading={loading}>
      <div className={styles.box}>
        {!showList.length ? (
          VCenterEmpty.render()
        ) : (
          <Row style={{ margin: 0 }} gutter={[4, 4]}>
            {showList.map(item => (
              <Col key={item.attrKey} span={24} className={styles.item}>
                <Texty className={styles.item_label}>{item.attrKey}</Texty>
                <Texty className={styles.item_value}>{item.attrValue || '--'}</Texty>
                {archiveFlag === 0 && (
                  <EditIcon
                    waybillNo={waybillNo}
                    value={item}
                    onChange={value => {
                      mutate(oldData => {
                        if (!oldData) return oldData
                        return oldData.map(d => {
                          if (d.attrKey === value.attrKey) return value
                          return d
                        })
                      })
                    }}
                  />
                )}
              </Col>
            ))}
          </Row>
        )}
      </div>
    </Card>
  )
}

function EditIcon({
  waybillNo,
  value,
  onChange,
}: {
  waybillNo: string
  value: IFiled
  onChange: (value: IFiled) => void
}) {
  const { token } = theme.useToken()

  const { attrKey, attrValue, type } = value
  const notEditable = isNotEditable(attrKey)

  const [loading, setLoading] = useState(false)
  const [open, setOpen] = useState(false)
  const [val, setVal] = useState(attrValue)
  const inputRef = useRef<InputRef>(null)

  useUpdateEffect(() => setVal(attrValue), [attrValue])

  const contentRender = () => {
    if (type === 'date') {
      const v = dayjs(val)
      return (
        <DatePicker
          style={{ width: 180, marginRight: 40 }}
          defaultOpen
          placement="bottomRight"
          value={v.isValid() ? v : undefined}
          onChange={(_v, vStr) => setVal(`${vStr || ''}`)}
        />
      )
    }
    return (
      <Input
        style={{ width: 250 }}
        placeholder={`请输入${attrKey}`}
        allowClear
        ref={inputRef}
        value={val}
        onChange={e => setVal(e.target.value)}
      />
    )
  }

  return (
    <Popconfirm
      icon={null}
      title={null}
      placement="topRight"
      description={contentRender()}
      destroyTooltipOnHide
      open={open}
      onOpenChange={v => {
        if (!v) setVal(attrValue)
        setOpen(v)
      }}
      afterOpenChange={v => v && inputRef.current?.focus()}
      okButtonProps={{ disabled: val.trim() === attrValue }}
      onConfirm={() => {
        const fn = async () => {
          const v = val.trim()
          try {
            setLoading(true)
            await apiSaveWaybillDynamicfield({ waybillNo, attrKey, attrValue: v })
            onChange({ ...value, attrValue: v })
          } finally {
            setLoading(false)
          }
        }
        fn()
      }}
    >
      <Button
        style={{ color: token.colorTextTertiary, opacity: open ? 1 : undefined }}
        className={styles.item_editIcon}
        type="text"
        loading={loading}
        disabled={notEditable || loading}
        icon={notEditable ? <StopOutlined /> : <EditOutlined />}
      />
    </Popconfirm>
  )
}
